package validate

import (
	"errors"
	"fmt"
	"net"
	"regexp"
	"strconv"
	"strings"
)

func ValidateSecret(in string) error {
	hasLower := regexp.MustCompile(`[a-z]`)
	hasUpper := regexp.MustCompile(`[A-Z]`)
	hasNumber := regexp.MustCompile(`[0-9]`)
	if len(in) >= 8 && hasLower.MatchString(in) && hasUpper.MatchString(in) && hasNumber.MatchString(in) {
		return nil
	}
	return errors.New("the password  must longer than 8 chars with at least 1 uppercase letter, 1 lowercase letter and 1 number")
}

func ValidateEmail(email string) error {

	if len(email) > 0 {
		if m, _ := regexp.MatchString(`^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$`, email); !m {
			return errors.New("Email with illegal format ")
		}
	} else {
		return errors.New("Email can't be empty ")
	}

	return nil
}

func ValidatePort(port string) error {

	if port == "" {
		return errors.New("port can't be empty ")
	}

	match, err := regexp.MatchString("^[0-9]*$", port)
	if err != nil {
		return fmt.Errorf("port %s with illegal format ", port)
	}

	i, err := strconv.Atoi(port)
	if err != nil {
		return fmt.Errorf("port %s with illegal format ", port)
	}
	if i < 0 || i > 65535 {
		return fmt.Errorf("port %s with illegal format ", port)
	}

	if match == false {
		return fmt.Errorf("port %s with illegal format ", port)
	}

	return nil
}

func ValidateIP(ip string) error {

	if len(ip) > 0 {
		if a := net.ParseIP(ip); a == nil {
			return fmt.Errorf("IP %s with illegal format ", ip)
		}
	} else {
		return errors.New("IP can't be empty ")
	}

	return nil
}
func ValidateCIDR(ipCIDR string) error {

	if len(ipCIDR) > 0 {
		if _, _, err := net.ParseCIDR(ipCIDR); err != nil {
			return fmt.Errorf("CIDR IP %s with illegal format ", ipCIDR)
		}
	} else {
		return fmt.Errorf("CIDR IP can't be empty")
	}

	return nil
}

// IsIllegalLength ...
func IsIllegalLength(s string, min int, max int) bool {
	if min == -1 {
		return len(s) > max
	}
	if max == -1 {
		return len(s) <= min
	}
	return len(s) < min || len(s) > max
}

// IsContainIllegalChar ...
func IsContainIllegalChar(s string, illegalChar []string) bool {
	for _, c := range illegalChar {
		if strings.Index(s, c) >= 0 {
			return true
		}
	}
	return false
}
func IsValidPort(port int) bool {
	return port > 0 && port < 65535
}
